<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 其他访问统计功能那个（暂未使用）
 **/
class OtherAccessNum extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;


    protected $table = 'other_access_num';

    /**
     * 记录浏览量
     * @param type 1 数字阅读   2 图书到家
     * @return void
     */
    public function add($type = 1 , $data = [])
    {
        $time = time();
        $year = date("Y", $time);
        $month = date("m", $time);
        $day = date("d", $time);

        $browse = $this->where('type', $type)->where('yyy', $year)->where('mmm', $month)->where('ddd', $day)->first();
        if ($browse) {
            $browse->total_num ++;
            return $browse->save();
        } else {
            $this->yyy = $year;
            $this->mmm = $month;
            $this->ddd = $day;
            $this->type = $type;
            $this->total_num = 1;
            return $this->save();
        }
    }

    /**
     * 数字资源点击量、图书到家点击量
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $type 1 数字阅读  2 图书到家
     */
    public function getClickNumber($type = 1 , $start_time = null, $end_time = null){
        $number = $this->where(function($query) use($type , $start_time , $end_time){
            if($type){
                $query->where('type' , $type);
            }
            if($start_time && $end_time){
                $query->whereBetween('create_time' , [$start_time , $end_time]);
            }
        })->sum('total_num');
        return $number;
    }

     /**
     * 点击量统计(折线图)
     * @param $type 1 数字阅读  2 图书到家
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     */
    public function clickStatistics($type = null, $start_time = null, $end_time = null)
    {
        if (date('Y-m-d' , strtotime($start_time)) == date('Y-m-d' , strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("sum(total_num) as number")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("sum(total_num) as number")];
        }
    
        $res = $this->select($field)->where(function ($query) use ($type, $start_time, $end_time) {
            if ($type) {
                $query->where('type', $type);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->orderBy('times')
            ->groupBy('times')
            ->get()
            ->toArray();

        return $res;
    }


}
